<?php
/**
 * Created by PhpStorm.
 * User: ChenYifan
 * Date: 2015/8/7
 * Time: 9:59
 */

namespace GatewayWorker\Lib;

/**
 * 数据库类
 */
class MongoDB
{
    /**
     * 实例数组
     * @var array
     */
    protected static $instance = array();

    /**
     * 获取实例
     * @param string $config_name
     * @throws \Exception
     */
    public static function instance($config_name)
    {
        if(!isset(\Config\MongoDB::$$config_name))
        {
            echo "\\Config\\Db::$config_name not set\n";
            throw new \Exception("\\Config\\Db::$config_name not set\n");
        }

        if(empty(self::$instance[$config_name]))
        {
            $config = \Config\MongoDB::$$config_name;
            self::$instance[$config_name] = new \MongoClient($config['server'],$config['options']);
        }

        return self::$instance[$config_name];
    }

    /**
     * 关闭数据库实例
     * @param string $config_name
     */
    public static function close($config_name)
    {
        if(isset(self::$instance[$config_name]))
        {
            self::$instance[$config_name]->close();
            self::$instance[$config_name] = null;
        }
    }

}
